<template>
  <div class="  container">
    <router-view></router-view>
    <div class="index">
      <Header />
      <div class="main-center2 " style="height: auto; margin-bottom:  0px;">
        <div class="test-con">
          <div class="test-con-list">
            <div class="test-tit">
              <label class="fl">{{ testInfo.name }}</label>
              <h1>
                {{ title }}：
                <span v-if="testInfo.limitdata == 1">{{ msTime.minutes }}:{{ msTime.seconds }}</span>
                <span v-else>不限时</span>
              </h1>
              <label class="fr" @click="goNext()">交卷</label>
            </div>
            <div class="test-c-area">
              <div class="test-left">
                <h3 class="dtk-tit">
                  答题卡
                  <label>总分{{ testInfo.pointslimit }}</label>
                </h3>
                <div class="" style="height: 855px;overflow-y: auto;">
                  <div class="" v-for="(item, index) in info" :key="index">
                    <p class="bt2">{{ item.type }}</p>
                    <span class="ta" v-for="(items, indexs) in item.list" :key="indexs">
                      <span v-if="truedata == 0">
                        <a class="current" v-if="items.id == typeCurrent && items.answer == undefined" @click="changeCurrent(items.id)">{{ indexs + 1 }}</a>
                        <a class=" cur" v-if="item.id != typeCurrent && items.answer != undefined" @click="changeCurrent(items.id)">{{ indexs + 1 }}</a>
                        <a class="" v-if="items.id != typeCurrent && items.answer == undefined" @click="changeCurrent(items.id)">{{ indexs + 1 }}</a>
                      </span>
                      <span v-else>
                        <a class="current" v-if="items.id == typeCurrent && items.answer == undefined">{{ indexs + 1 }}</a>
                        <a class=" cur" v-if="item.id != typeCurrent && items.answer != undefined">{{ indexs + 1 }}</a>
                        <a class="" v-if="items.id != typeCurrent && items.answer == undefined">{{ indexs + 1 }}</a>
                      </span>
                    </span>
                  </div>
                </div>
              </div>
              <div class="" v-for="(item, index) in testData" :key="index">
                <div class="test-right" v-if="index == current">
                  <h3 class="dtk-tit">
                    {{ item.typedata_text }}
                    <span v-if="item.typedata_text == '单选题'">（{{ first.sore }}分，共{{ first.list.length }}题）</span>
                    <span v-if="item.typedata_text == '多选题'">（{{ second.sore }}分，共{{ second.list.length }}题）</span>
                    <span v-if="item.typedata_text == '判断题'">（{{ third.sore }}分，共{{ third.list.length }}题）</span>
                    <span v-if="item.typedata_text == '填空题'">（{{ four.sore }}分，共{{ four.list.length }}题）</span>
                    <label>第{{ index + 1 }}题</label>
                  </h3>
                  <p class="k-tit">{{ item.title }}</p>
                  <div class="" v-for="(items, indexs) in item.options">
                    <el-radio-group @change="changeLable(item)" v-model="item.answer" v-if="item.typedata_text == '单选题'">
                      <P class="tt1">
                        <el-radio :label="items.key">{{ items.value }}</el-radio>
                      </P>
                    </el-radio-group>
                  </div>
                  <p class="k-tit"></p>
                  <div class="" v-for="(items, indexs) in item.options">
                    <el-checkbox-group v-model="item.changeanswer" v-if="item.typedata_text == '多选题'" @change="changeBox(item.id, checkList, item)">
                      <P class="tt1">
                        <el-checkbox :label="items.key">{{ items.value }}</el-checkbox>
                      </P>
                    </el-checkbox-group>
                  </div>
                  <div class="">
                    <el-radio-group @change="changeRadio(item)" v-model="item.answer" v-if="item.typedata_text == '判断题'">
                      <P class="tt1"><el-radio label="1">对</el-radio></P>
                      <P class="tt1"><el-radio label="0">错</el-radio></P>
                    </el-radio-group>
                  </div>
                  <div class="test-area" v-if="item.typedata_text == '填空题'">
                    <el-input v-model="item.answer" @input="getInput(item)" type="textarea" placeholder="请输入您的答案" rows="8" show-word-limit></el-input>
                  </div>
                  <div class="mt30"></div>
                  <div class="mt90"></div>
                  <div class="mt10 baseAct txt-l">
                    <button class="sure" type="info" v-if="current > 0" @click="goBackQestion()">上一题</button>
                    <button @click="goNextQestion(current)" v-if="current < testData.length - 1" class="sure">下一题</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from '../../components/header.vue';
import Copyright from '../../components/copyright2.vue';

export default {
  data() {
    return {
      truedata: '', //是否解析，0不解析，1解析
      isLeft: false,
      token: localStorage.getItem('token'),
      id: '',
      info: '', //试卷答题卡
      type: '单选题',
      typeCurrent: '', //试卷题型
      testData: [], //试卷所有考题
      current: 0, //第几题
      checkList: [],
      testInfo: '',
      first: '', //单选
      second: '', //多选
      third: '', //判断
      four: '', //填空
      isSure: false, //是否正确
      sureCheck: [], //正确答案
      msTime: {
        minutes: '30', //分钟
        seconds: '00' //秒
      },
      intervalTime: '',
      isDownTime: true,
      beginTime: '', //开始时间
      endTime: '', //结束时间
      title: '剩余时间',
      windingdata: ''
    };
  },
  created() {
    this.beginTime = new Date().getTime();
    this.id = this.$route.query.id;
    this.getTestInfo(this.id);
    this.getTopInfo();
  },
  beforeDestroy() {
    clearInterval(this.intervalTime);
  },
  methods: {
    beginCount() {
      // 倒计时
      if (this.isDownTime) {
        this.intervalTime = setInterval(() => {
          if (Number(this.msTime.seconds) > 0) {
            this.msTime.seconds = Number(this.msTime.seconds) - 1;
          } else if (Number(this.msTime.minutes) > 0) {
            this.msTime.minutes = Number(this.msTime.minutes) - 1;
            this.msTime.seconds = Number(this.msTime.seconds) + 60 - 1;
          } else {
            clearInterval(this.intervalTime);
            this.intervalTime = '';
            if (this.windingdata == '0') {
              this.title = '超时';
              this.endCount();
            } else {
              var answerJson = [];
              this.endTime = new Date().getTime();
              this.testData.forEach(item => {
                if (item.answer != undefined && item.answer != '') {
                  var data = {};
                  data.qid = item.id;
                  data.ans = item.answer;
                  answerJson.push(data);
                }
              });
              let formData = {
                answerjson: JSON.stringify(answerJson),
                course_id: this.testInfo.course_id,
                begintime: parseInt(this.beginTime / 1000),
                overtime: parseInt(this.endTime / 1000),
                id: this.id
              };
              //console.log(formData);
              this.$api('getCourseList.addUserTopic', formData).then(res => {
                this.$message({
                  type: 'success',
                  message: '答卷时间到期,已提交答卷!'
                });
                this.$router.replace('/test2?id=' + this.id);
              });
            }
          }

          if (Number(this.msTime.seconds) < 10) {
            this.msTime.seconds = '0' + Number(this.msTime.seconds);
          }
          if (Number(this.msTime.minutes) < 10) {
            this.msTime.minutes = '0' + Number(this.msTime.minutes);
          }
        }, 1000);
      }
    },
    //正计时
    endCount() {
      this.msTime = {
        minutes: '00', //分钟
        seconds: '00' //秒
      };
      this.intervalTime = setInterval(() => {
        this.msTime.seconds = Number(this.msTime.seconds) + 1;
        if (this.msTime.seconds > 60) {
          this.msTime.minutes++;
          this.msTime.seconds = '00';
        }
        if (Number(this.msTime.seconds) < 10) {
          this.msTime.seconds = '0' + Number(this.msTime.seconds);
        }
        if (Number(this.msTime.minutes) < 10) {
          this.msTime.minutes = '0' + Number(this.msTime.minutes);
        }
      }, 1000);
    },
    //单选
    changeLable(item) {
      // if (this.truedata == '1') {
      //   item.options.forEach((items, index) => {
      //     if (items.answer == '1') {
      //       if (items.key == item.answer) {
      //         this.isSure = true;
      //       } else {
      //         this.isSure = false;
      //       }
      //     }
      //   });
      // }
    },
    changeRadio(item) {
      // if (item.judgedata == item.answer) {
      //   this.isSure = true;
      // } else {
      //   this.isSure = false;
      // }
    },
    //多选
    changeBox(id, checklist, item) {

      this.testData.forEach((item, index) => {
        if (item.id == id) {
          //console.log(item);
          if(item.changeanswer.length>0){
            item.answer=item.changeanswer.join('')
          }
          var answer1 = item.trueanswer.split('');

          for(var i=0 ;i<item.changeanswer.length;i++){
            if (answer1.indexOf(item.changeanswer[i]) != -1 && answer1.length == item.changeanswer.length) {
                item.isSure=true
              } else {
               item.isSure = false;
             break;
              }
          }
        }
      });
    }, //填空
    getInput(item) {
      // //console.log(item);
      // if (item.answer == item.options[0].value) {
      //   this.isSure = true;
      // } else {
      //   this.isSure = false;
      // }
    },
    //答题卡点击
    changeCurrent(id) {
      this.typeCurrent = id;
      this.testData.forEach((item, index) => {
        if (item.id == id) {
          this.current = index;
        }
      });
    },
    //获取试卷信息
    getTopInfo() {
      this.$api('getCourseList.getTopicInfo', { token: this.token, id: this.id }).then(res => {
        this.testInfo = res.data[0];
        this.truedata = this.testInfo.truedata;
        this.windingdata = this.testInfo.windingdata;
        this.msTime.minutes = this.testInfo.limitall.substring(0, this.testInfo.limitall.length - 3);
        this.msTime.seconds = this.testInfo.limitall.substring(this.testInfo.limitall.length - 2);
        if (this.testInfo.limitdata == 1) {
          this.beginCount();
          // this.title = '超时';
          // this.endCount();
        }
      });
    },
    //获取考题信息
    getTestInfo(id) {
      this.$api('getCourseList.getWxTopicCardList', { token: this.token, id: this.id }).then(res => {
        this.info = res.data;
        for (let item in this.info) {
          this.info[item].list.forEach((items, indexs) => {
            this.testData.push(items);
          });
        }
        this.first = this.info[1];
        this.second = this.info[2];
        this.third = this.info[3];
        this.four = this.info[4];
        this.typeCurrent = this.testData[0].id;
        //console.log(this.testData);
      });
    },
    goBackQestion() {
      if (this.current > 0) {
        this.current--;
        this.testData.forEach((item, index) => {
          if (this.current == index) {
            this.typeCurrent = item.id;
          }
        });
      }
    },
    goNextQestion(current) {
      if (this.truedata == '1') {
        for (var i = 0; i < this.testData.length; i++) {
          if (this.current == i) {
            if (this.testData[i].typedata_text == '多选题') {
              //console.log(this.testData[i]);
              if (this.testData[i].changeanswer != undefined) {
                var answer2 = this.testData[i].changeanswer;
              }
              var answer1 = this.testData[i].trueanswer;
              //console.log(this.isSure);
              if (this.testData[i].changeanswer.length == 0||this.testData[i].isSure==false) {
                this.$message({
                  message: '答错了，再想想吧',
                  type: 'warning'
                });
                break;
              } else {
                this.current++;

                break;
              }
            } else {
              //console.log('else2');
              if (this.testData[i].answer == undefined || this.testData[i].answer != this.testData[i].trueanswer) {
                this.$message({
                  message: '答错了，再想想吧',
                  type: 'warning'
                });
              } else {
                this.current++;
                this.checkList = [];

                break;
              }
            }
          }
        }
      } else {
        if (this.current < this.testData.length) {
          this.current++;
          this.testData.forEach((item, index) => {
            //console.log(item);
            if (this.current == index) {
              this.typeCurrent = item.id;
            }
          });
        }
      }
    },
    //交卷
    goNext() {
      if (this.truedata == '1') {
        if (this.testData[this.testData.length - 1].answer != this.testData[this.testData.length - 1].trueanswer) {
          this.$message({
            message: '最后一题似乎答错了，请仔细检查',
            type: 'warning'
          });
          return;
        }
      }
      var queNum = [];
      this.testData.forEach((item, index) => {
        if (item.answer != undefined && item.answer != '') {
          queNum.push(item);
        }
      });
      if (queNum.length != this.testData.length && this.truedata == '0') {
        this.$confirm('您未答完题，是否交卷?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            var answerJson = [];
            this.endTime = new Date().getTime();
            this.testData.forEach(item => {
              if (item.answer != undefined && item.answer != '') {
                var data = {};
                data.qid = item.id;
                data.ans = item.answer;
                answerJson.push(data);
              }
            });

            let formData = {
              answerjson: JSON.stringify(answerJson),
              course_id: this.testInfo.course_id,
              begintime: parseInt(this.beginTime / 1000),
              overtime: parseInt(this.endTime / 1000),
              id: this.id
            };
            //console.log(formData);
            this.$api('getCourseList.addUserTopic', formData).then(res => {
              this.$message({
                type: 'success',
                message: '交卷成功!'
              });
              this.$router.replace('/test2?id=' + this.id);
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消交卷或交卷失败'
            });
          });
      } else {
        this.$confirm('是否交卷?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.endTime = new Date().getTime();
            var answerJson = [];
            this.testData.forEach(item => {
              if (item.answer != undefined && item.answer != '') {
                var data = {};
                data.qid = item.id;
                data.ans = item.answer;
                answerJson.push(data);
              }
            });
            let formData = {
              answerjson: JSON.stringify(answerJson),
              course_id: this.testInfo.course_id,
             begintime: parseInt(this.beginTime / 1000),
             overtime: parseInt(this.endTime / 1000),
              id: this.id
            };
            //console.log(formData);
            this.$api('getCourseList.addUserTopic', formData).then(res => {
              this.$message({
                type: 'success',
                message: '交卷成功!'
              });
              this.$router.replace('/test2?id=' + this.id);
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消交卷或交卷失败'
            });
          });
      }
    },
    goJG() {
      this.$router.push('/courseList');
    },
    goCollect() {
      this.$router.push('/courseCollect');
    }
  },
  components: { Header, Copyright }
};
</script>

<style lang="scss" scoped>
/deep/ .el-input__inner {
  height: 36px;
  line-height: 35px;
  outline: 0;
}
</style>
